/**
* @Descripttion: 未描述
* @Author: Chenbangquan
* @version: 1.0.0
* @CreateDate 2023-04-10 15:08
* @LastEditors: cbq
* @LastEditTime: 2023-04-10
*/
<template>
  <div>
    <el-form ref="ruleFormRef" :model="tableForm" inline class="ruleForm">
      <el-form-item label="角色名：">
        <el-input
                v-model="tableForm.queryRo.name"
                placeholder="请输入角色名称"
                style="width: 180px"
                clearable
        />
      </el-form-item>
      <!--<el-form-item label="状态：" prop="name">-->
        <!--<el-select v-model="ruleForm.queryRo.status" clearable style="width: 136px">-->
          <!--<el-option label="可用" :value="1" />-->
          <!--<el-option label="禁用" :value="2" />-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button type="primary" @click="getTableList">查询</el-button>
        <el-button type="success" @click="addUser()">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableList" style="width: 100%" v-loading="loading">
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="name" label="角色名称" align="center" />
      <el-table-column prop="id" label="ID" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column prop="createTime" label="是否启用" align="center">
        <template #default="scope">
          <span>{{scope.row.status == 1 ? '启用':'禁用'}}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="160">
        <template #default="scope">
          <!--<el-button link type="primary" size="small">Detail</el-button>-->
          <el-button link type="primary" size="small" @click="editRole(scope.row)">编辑</el-button>
          <el-button link type="danger" size="small" @click="delRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <footer class="pagination">
      <el-pagination
              v-model:currentPage="tableForm.current"
              v-model:page-size="tableForm.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              small
      />
    </footer>
    <el-drawer
            v-model="drawer"
            :title="ruleForm.data.id ? '编辑角色': '新增角色'"
            :direction="direction">
      <el-form
              ref="ruleFormRef"
              :model="ruleForm.data"
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
              :size="formSize"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.data.name" />
        </el-form-item>
<!--        <el-form-item label="组织机构：" prop="operatorId">-->
        <!--          <el-select v-model="ruleForm.data.operatorId" clearable style="width: 136px">-->
        <!--            <el-option label="平台运营商" :value="1" />-->
        <!--            <el-option label="集团客户" :value="2" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="菜单权限">
          <el-tree
                  ref="treeRef"
                  show-checkbox
                  node-key="id"
                  :data="treeList"
                  @check="currentChecked"
                  :default-checked-keys="permission"
                  :props="defaultProps">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="status"></el-switch>
        </el-form-item>
        <el-form-item label="首页地址" prop="indexUrl">
          <el-input v-model="ruleForm.data.indexUrl" placeholder />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <!--<el-button @click="cancelForm">取消</el-button>-->
          <el-button type="primary"  @click="submitForm(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
    import { ref, reactive, onMounted,nextTick} from 'vue'
    import { FormInstance, FormRules,ElMessageBox } from 'element-plus'
    import { ElMessage } from 'element-plus'
    import { menuGroupAll} from '@/api/apis/user'
    import {postAddAuth,postRoleList,postEditRoleById,delRoleById} from '@/api/authApi/authApi'
    const drawer = ref(false)
    const direction = ref('rtl')
    const formSize = ref('default')
    const status = ref(true)
    const permission = ref([]) //树默认选中
    const ruleFormRef = ref<FormInstance>()
    const defaultProps = {
        children: 'childMenuList',
        label: 'name',
    }
    const ruleForm = reactive({
        data:{
            indexUrl: "",
            name: "",
            status: 1,
            operatorId: 1,//组织机构Id加_类型（1平台运营商或2集团客户）
            permission:'',
        }
    })
    const rules = reactive<FormRules>({
        name: [
            // { required: true, message: 'Please input Activity name', trigger: 'blur' },
            { required: true, message: '请填写角色名称', trigger: 'blur' },
            // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
        ],
        operatorId: [
            { required: true, message: '请选择组织机构', trigger: 'blur' },
        ],
        indexUrl: [
            { required: true, message: '请填写角色登录首页地址', trigger: 'blur' },
        ],
    })
    onMounted(() => {
        getTableList()
    })
    //选中节点
    const currentChecked = (nodeObj, SelectedObj)=>{
        console.log('nodeObj',nodeObj)
        console.log('SelectedObj',SelectedObj)
        let arr = []
        SelectedObj.checkedNodes.forEach((item,index)=>{
            arr.push(item.id,item.parentId)
        })
        console.log('arrarrarr',arr)
        ruleForm.data.permission = [...new Set(arr)].join(',')
        console.log(ruleForm.data.permission)   // 这是选中的节点的key数组

    }
    //表格数据
    const treeList = ref([])
    //获取菜单数据
    const getTreeList = async () => {
        let { data } = await menuGroupAll()
        treeList.value = data.data
    }
    //编辑
    const editRole = (row)=>{
        getTreeList()
        let data = {...row}
        ruleForm.data= {...row}
        status.value = ruleForm.data.status == 1 ? true : false
        permission.value = data.permission.split(',')
        drawer.value = true
        console.log('ruleForm',ruleForm.data)
    }
    const tableForm = reactive({
        asc: true,
        queryRo: {
            name:''
        },
        searchCount: true,
        current: 1,
        pageSize: 20,
    })
    //总数
    const total = ref(0)
    //表格数据
    const tableList = ref([])
    //加载
    const loading = ref(false)
    //获取表格数据
    const getTableList = async () => {
        loading.value = true
        let res = await postRoleList(tableForm)
        tableList.value = res.data.data.rows
        total.value = Number(res.data.data.total)
        loading.value = false
    }
    //改变每页条数
    const handleSizeChange = (val: number) => {
        tableForm.current = 1
        tableForm.pageSize = val
        getTableList()
    }
    //改变当前页数
    const handleCurrentChange = (val: number) => {
        tableForm.current = val
        getTableList()
    }
    const delRole = (row)=>{
        ElMessageBox.confirm(
            '您确定要删除该角色吗?',
            '注意',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                let res = await delRoleById(row.id)
                console.log(res)
                if(res.data.code == 200){
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getTableList()
                }

            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消删除',
                })
            })
    }
    //新增
    const submitForm = async (formEl: FormInstance | undefined) => {
        if (!formEl) return
        await formEl.validate(async (valid, fields) => {
            if (valid) {
                let res, message
                ruleForm.data.status = status.value ? 1 : 2
                if(ruleForm.data.id){

                    console.log('ruleForm.data',ruleForm.data)
                    res = await postEditRoleById(ruleForm.data)
                    message = '编辑成功！'
                }else {
                    res = await postAddAuth(ruleForm.data)
                    message = '新增成功！'
                }
                if(res.data.code == 200){
                    ElMessage({
                        message: message,
                        type: 'success',
                    })
                    getTableList()
                    drawer.value = false
                }
            } else {
                console.log('error submit!', fields)
            }
        })
    }
    const addUser = async (formEl: FormInstance | undefined) => {
        drawer.value = true
        getTreeList()
        permission.value = []
        let  obj = {
            indexUrl: "",
            name: "",
            status: 1,
            operatorId:1,//组织机构Id加_类型（1平台运营商或2集团客户）
            permission:'',
        }
        ruleForm.data = obj
    }
</script>

<style scoped>

</style>
